//  专家解答 对话界面
//  zhuShouViewController.m
//  chat
//
//  Created by ios-23 on 17/4/26.
//  Copyright © 2017年 ios-23. All rights reserved.
//

#import <GTMBase64.h>
#import "zhuShouViewController.h"
#import "MKJChatModel.h"
#import "MKJChatTableViewCell.h"
#import "LGPhoto.h"
#import "DataUtils.h"
#import "TimeTools.h"

#define URL_getChatlist @"/api/messages/1/SYSTEM_MESSAGE/all?sort=createdDate,desc&page=0&size=10000"
#define URL_sendMessage @"/api/messages"
#define URL_ClearUnread @"/api/message-boxes/clearUnreadCount/SYSTEM_MESSAGE"

@interface zhuShouViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,LGPhotoPickerViewControllerDelegate,LGPhotoPickerBrowserViewControllerDataSource,LGPhotoPickerBrowserViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewBottomCostraint;
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic,strong) NSMutableArray *chatArr;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewCostraint;
@property (nonatomic, strong) NSNumber *myuid;

@property (nonatomic, assign) LGShowImageType showType;
@property (nonatomic, strong)NSMutableArray *LGPhotoPickerBrowserPhotoArray;
@property(nonatomic,strong)NSMutableArray *selectedPhott;
@end
static NSString *identify = @"MKJChatTableViewCell";

@implementation zhuShouViewController
- (IBAction)camera:(UIButton *)sender {
    [self presentCameraContinuous];
    
}
- (IBAction)photo:(UIButton *)sender {
    [self presentPhotoPickerViewControllerWithStyle:LGShowImageTypeImagePicker];
}
//显示更多操作工具栏（拍照，相册）
- (IBAction)addViewAction:(UIButton *)sender {
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        self.bottomViewCostraint.constant = 0;
        [self.view layoutIfNeeded];
    } completion:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //[self.tableView registerClass:[MKJChatTableViewCell class] forCellReuseIdentifier:identify];
    
    self.textField.inputAccessoryView = [UIView new];
    
    self.title=@"在线客服";
    // 小技巧，用了之后不会出现多余的Cell
    UIView *view = [[UIView alloc] init];
    self.tableView.tableFooterView = view;
    
    // 底部输入栏
    self.textField.returnKeyType = UIReturnKeySend;//变为搜索按钮
    self.textField.delegate = self;
    self.textField.layer.masksToBounds=YES;
    self.textField.layer.cornerRadius=18;
    self.textField.layer.borderWidth=.5;
    self.textField.layer.borderColor=[UIColor colorWithRed:235/255.0 green:234/255.0 blue:235/255.0 alpha:1.0].CGColor;
    // 注册键盘的通知hide or show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 增加手势，点击弹回
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)];
    [self.view addGestureRecognizer:tap];
    //导航栏左侧返回箭头按钮
    UIImage *leftImage=[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftButtonItem=[[UIBarButtonItem alloc]initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem=leftButtonItem;
    
    //取自己的UID
    self.myuid = [DataUtils getMyUID];
    
    //请求对话列表
     [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_getChatlist] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
         NSArray *jsonArr = (NSMutableArray*)responseObject;
         if (jsonArr.count > 0) {
             for (id chat in jsonArr) {
                 [self.chatArr addObject:[DataUtils getChatMdodelFromJsonObj:chat selfUID:self.myuid]];
             }
             /*
             long i = self.chatArr.count-2;
             MKJChatModel *current_model = self.chatArr[i];
             MKJChatModel *last_model = self.chatArr[i+1];
             last_model.dSender.id = @136;
             last_model.dSender.avatar = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1513245277403&di=480c71840ea37f3d002424c04ee2ad6a&imgtype=0&src=http%3A%2F%2Fp1.qqyou.com%2Ftouxiang%2FUploadPic%2F2015-4%2F15%2F201504151133475846.jpg";
             last_model.dReceiver.id = @1;
             last_model.isRight = YES;
             last_model.content = @"请问术后一年血压142/86/73算不算高？6点吃了降压药，8点还要在吃吗？";
             current_model.dSender.id = @1;
             current_model.dReceiver.id = @136;
             current_model.content = @"正常血压是90/60~139/89，理想血压小于120/80，您的血压还是偏高";
             
             [self.chatArr removeAllObjects];
             [self.chatArr addObject:current_model];
             [self.chatArr addObject:last_model];
             */
             for (int i=0; i<self.chatArr.count-1; i++) {
                 MKJChatModel *current_model = self.chatArr[i];
                 MKJChatModel *last_model = self.chatArr[i+1];
                 int interval = [TimeTools getIntervalSecond:current_model.createdDate time2:last_model.createdDate];
                 if (interval>300) {
                     current_model.isShowTime = YES;
                 }
                 else {
                     current_model.isShowTime = NO;
                 }
             }
            
         }
         [self.tableView reloadData];
         if (self.chatArr.count != 0) {
             [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
         }
         
         //清除未读消息数
         [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_ClearUnread]
                                           parameters:nil
                                             delegate:nil
                                           requestTag:2
                                         successBlock:nil];
     }];
}
-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)click:(UITapGestureRecognizer *)tap
{
    [UIView animateWithDuration:0.5 animations:^{
        self.bottomViewCostraint.constant = -110;
        [self.view layoutIfNeeded];
    } completion:nil];
    [self.view endEditing:YES];
}
//输入完毕
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (![textField.text isEqualToString:@""])
    {
        MKJChatModel *chatModel = [[MKJChatModel alloc] init];
        chatModel.content = textField.text;
        chatModel.isRight = YES;
        [self.chatArr insertObject:chatModel atIndex:0];
        [self postTextMessage:chatModel.content];
    }
    [self.tableView reloadData];
    // 滚到底部  scroll so row of interest is completely visible at top/center/bottom of view
    if (self.chatArr.count != 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    self.textField.text=@"";
    [self.view endEditing:YES];
    return YES;
}
// 监听键盘弹出
- (void)keyBoardShow:(NSNotification *)notification
{
    
    [self.view bringSubviewToFront:self.inputView];
    //获取键盘高度
    CGFloat keyBoardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    //动画持续时间
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //动画选项
    NSInteger option = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    self.viewBottomCostraint.constant = keyBoardHeight-111;
    [UIView animateWithDuration:duration delay:0 options:option animations:^{
        //不断更新约束
        [self.view layoutIfNeeded];
    } completion:nil];
    
    
    //让tableView 滚动到最后一行
    if (self.chatArr.count != 0)
    {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}
// 监听键盘隐藏
- (void)keyboardHide:(NSNotification *)notification
{
    //动画持续时间
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //动画选项
    NSInteger option = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    self.viewBottomCostraint.constant = 0;
    [UIView animateWithDuration:duration delay:0 options:option animations:^{
        //不断更新约束
        [self.view layoutIfNeeded];
    } completion:nil];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    debugLog(@"第 %ld section, item_count:%ld", (long)section, (long)self.chatArr.count);
    return self.chatArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 定义cell标识  每个cell对应一个自己的标识
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",(long)indexPath.section,(long)indexPath.row];
    // 通过不同标识创建cell实例
    MKJChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[MKJChatTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    //取自己的UID
    MKJChatModel *model = self.chatArr[self.chatArr.count - 1 - indexPath.row];
    if ([model.type compare:@"text"]==0) {
        [cell refreshCell:model];
    }
    else{
        [cell photoCell:model];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat h = 0;
    MKJChatModel *model = self.chatArr[self.chatArr.count - 1 - indexPath.row];
    if ([model.type compare:@"image"]==0) {
        h = 100+45;
        if (model.isShowTime) {
            h += SENDTIME_H;
        }
        return h;
    }
    CGRect rec =  [model.content boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}
                                              context:nil];
    h = rec.size.height + 50;
    if (model.isShowTime) {
        h += SENDTIME_H;
    }
    //debugLog(@"[ChatCell]indexPath:(%ld,%ld),h:%f", indexPath.section, indexPath.row, h);
    return h;
    
}

- (NSMutableArray *)chatArr
{
    if (_chatArr == nil) {
        _chatArr = [[NSMutableArray alloc] init];
    }
    return _chatArr;
}

- (NSMutableArray *)selectedPhott
{
    if (_selectedPhott == nil) {
        _selectedPhott = [[NSMutableArray alloc] init];
    }
    return _selectedPhott;
}


/**
 *  初始化相册选择器
 */
- (void)presentPhotoPickerViewControllerWithStyle:(LGShowImageType)style {
    LGPhotoPickerViewController *pickerVc = [[LGPhotoPickerViewController alloc] initWithShowType:style];
    pickerVc.status = PickerViewShowStatusCameraRoll;
    pickerVc.maxCount = 1;   // 最多能选9张图片
    pickerVc.delegate = self;
    self.showType = style;
    [pickerVc showPickerVc:self];
}

/**
 *  初始化自定义相机（连拍）
 */
- (void)presentCameraContinuous {
    ZLCameraViewController *cameraVC = [[ZLCameraViewController alloc] init];
    // 拍照最多个数
    cameraVC.maxCount = 1;
    // 连拍
    cameraVC.cameraType = ZLCameraContinuous;
    cameraVC.callback = ^(NSArray *cameras){
        //在这里得到拍照结果
        //数组元素是ZLCamera对象
         ZLCamera *canamerPhoto = cameras[0];
         UIImage *image = canamerPhoto.photoImage;
        MKJChatModel *chatModel = [[MKJChatModel alloc] init];
        chatModel.isRight = 1;//arc4random() % 2; // 0 or 1
        chatModel.type = @"image";
        [chatModel.images addObject:image];
        [self.chatArr insertObject:chatModel atIndex:0];
        
        if (self.chatArr.count != 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    };
    [cameraVC showPickerVc:self];
}

#pragma mark - LGPhotoPickerViewControllerDelegate
- (void)pickerViewControllerDoneAsstes:(NSArray *)assets isOriginal:(BOOL)original{
    [self.selectedPhott removeAllObjects];
    for (LGPhotoAssets *photo in assets) {
        //原图
        [self.selectedPhott addObject:photo.originImage];
    }
    
    if (self.selectedPhott.count>0)
    {
        MKJChatModel *chatModel = [[MKJChatModel alloc] init];
        chatModel.isRight = 1;//arc4random() % 2; // 0 or 1
        chatModel.type = @"image";
        [chatModel.images addObject:self.selectedPhott[0]];
        [self.chatArr insertObject:chatModel atIndex:0];
        [self postImageMessage:chatModel.images[0]];
    }
    
    [self.tableView reloadData];
    
    // 滚到底部  scroll so row of interest is completely visible at top/center/bottom of view
    if (self.chatArr.count != 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}

#pragma mark - LGPhotoPickerBrowserViewControllerDataSource
- (NSInteger)photoBrowser:(LGPhotoPickerBrowserViewController *)photoBrowser numberOfItemsInSection:(NSUInteger)section{
    if (self.showType == LGShowImageTypeImageBroswer) {
        return self.LGPhotoPickerBrowserPhotoArray.count;
    } else {
        NSLog(@"非法数据源");
        return 0;
    }
}

- (id<LGPhotoPickerBrowserPhoto>)photoBrowser:(LGPhotoPickerBrowserViewController *)pickerBrowser photoAtIndexPath:(NSIndexPath *)indexPath{
    if (self.showType == LGShowImageTypeImageBroswer) {
        return [self.LGPhotoPickerBrowserPhotoArray objectAtIndex:indexPath.item];
    } else {
        NSLog(@"非法数据源");
        return nil;
    }
}

#pragma mark - 业务逻辑
//发送文本消息
-(void)postTextMessage:(NSString*)text{
    MKJChatModel *model = [MKJChatModel new];
    model.type = @"text";
    model.content = text;
    [self postMessage:model];
}
//发送图片消息
-(void)postImageMessage:(UIImage*)image{
    MKJChatModel *model = [MKJChatModel new];
    model.type = @"image";
    NSData *img_data = UIImageJPEGRepresentation(image, 1.0f);
    NSData *base64_img = [GTMBase64 encodeData:img_data];
    NSString *to_str = [[NSString alloc]initWithData:base64_img encoding:NSASCIIStringEncoding];
    [model.images addObject:to_str];
    [self postMessage:model];
}
//发送消息
-(void)postMessage:(MKJChatModel*)message{
    message.model = @"SYSTEM_MESSAGE";
    
    YZEChatTargetModel *sender = [YZEChatTargetModel new];
    sender.id = self.myuid;
    NSDictionary *userinfo = [UserDefaultsTools getUserDefaultsForKey:USERINFO_KEY];
    sender.sickpersonId = [userinfo objectForKey:@"id"];
    YZEChatTargetModel *receiver = [YZEChatTargetModel new];
    receiver.id = @1;
    message.dSender = sender;
    message.dReceiver = receiver;
    
    [[YZENetwork sharedInstace]postRequestWithUrl:[BASE stringByAppendingString:URL_sendMessage]
                                       parameters:[message mj_keyValuesAdd]
                                         delegate:self
                                       requestTag:1
                                     successBlock:^(id responseObject)
    {
        
    }];
}


@end
